package org.example.test.test04.t01;

import java.io.IOException;
import java.io.InputStream;
import java.sql.*;
import java.util.Properties;

/**
 *
 */
public class DBUtils {
    private static String driver;
    private static String url;
    private static String user;
    private static String password;

    //一般情况下，我们将加载驱动的步骤，放到static静态块中
    static {
        //读取src路径下的db.properties
        InputStream is = DBUtils.class.getClassLoader().getResourceAsStream("db.properties");

        Properties properties = new Properties();

        try {
            //将输入流中的数据（4组键值对），装载到properties集合中
            properties.load(is);
        } catch (IOException e) {
            e.printStackTrace();
        }

        //通过key取得value值
        driver = properties.getProperty("jdbc.driver");
        url = properties.getProperty("jdbc.url");
        user = properties.getProperty("jdbc.user");
        password = properties.getProperty("jdbc.password");

        try {
            Class.forName(driver);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }finally {
            if (null!=is){
                try {
                    is.close();
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }
        }
    }
    // 取得连接
    public static Connection getConn() throws SQLException {
        Connection conn = DriverManager.getConnection(url,user,password);
        return conn;
    }

    // 关闭资源
    /*
        对于资源的关闭，分为两种情况
        添加 修改 删除 需要关闭的资源有 Statement  Connection
        查询 需要关闭的资源有 ResultSet Statement  Connection
     */
    public static void close(Connection conn, PreparedStatement ps, ResultSet rs){
        if (null != rs){
            try {
                rs.close();
            } catch (SQLException e) {
                throw new RuntimeException(e);
            }
        }
        if (null != ps){
            try {
                ps.close();
            } catch (SQLException e) {
                throw new RuntimeException(e);
            }
        }
        if (null != conn){
            try {
                conn.close();
            } catch (SQLException e) {
                throw new RuntimeException(e);
            }
        }
    }
    // 方法重载
    public static void close(Connection conn,PreparedStatement ps){
        if (null != ps){
            try {
                ps.close();
            } catch (SQLException e) {
                throw new RuntimeException(e);
            }
        }
        if (null != conn){
            try {
                conn.close();
            } catch (SQLException e) {
                throw new RuntimeException(e);
            }
        }
    }
}
